package com.nc.delivery_project.client.schedules;

import com.google.gwt.activity.shared.AbstractActivity;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.shared.EventBus;
import com.google.gwt.place.shared.Place;
import com.google.gwt.user.client.ui.AcceptsOneWidget;
import com.google.web.bindery.requestfactory.shared.Receiver;
import com.google.web.bindery.requestfactory.shared.ServerFailure;
import com.nc.delivery_project.client.ClientFactory;
import com.nc.delivery_project.client.request.ScheduleRequest;
import com.nc.delivery_project.shared.proxy.ScheduleProxy;

import java.util.List;

/**
 * Created by DRAGON on 18.01.2015.
 */
public class SchedulesActivity extends AbstractActivity implements SchedulesPresenter {

    private SchedulesView view;
    private ClientFactory clientFactory;

    public SchedulesActivity(SchedulesPlace place, ClientFactory clientFactory) {
        this.clientFactory = clientFactory;
    }

    @Override
    public void start(AcceptsOneWidget panel, EventBus eventBus) {
        if (view == null) {
            view = new SchedulesView();
        }

        view.setPresenter(this);
        panel.setWidget(view.asWidget());
        view.start();

        loadSchedules();
    }

    @Override
    public void goTo(Place place) {
        clientFactory.getPlaceController().goTo(place);
    }

    @Override
    public ClientFactory getClientFactory() {
        return clientFactory;
    }

    @Override
    public void loadSchedules() {
        final ScheduleRequest scheduleRequest = clientFactory.getRequestFactory().createScheduleRequest();

        scheduleRequest.read().with("origin","destination","transportCompany","currency").fire(new Receiver<List<ScheduleProxy>>() {
            @Override
            public void onSuccess(List<ScheduleProxy> response) {
                GWT.log("success");
                GWT.log(response.get(0).getOrigin().getAddress());
                GWT.log(response.get(1).getDestination().getAddress());
             //   GWT.log(response.get(2).getTransportCompany().getTitle());
                GWT.log(response.get(3).getCurrency().getTitle());
                view.setDataList(response);
            }

            @Override
            public void onFailure(ServerFailure error) {
                super.onFailure(error);
                GWT.log(error.toString());
            }
        });

    }
}
